package com.example.yimai.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.yimai.entity.ProductCategory;
import com.example.yimai.mapper.ProductCategoryMapper;
import com.example.yimai.service.ProductCategoryService;
import com.example.yimai.utils.ParamUtil;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class ProductCategoryServiceImpl extends ServiceImpl<ProductCategoryMapper, ProductCategory> implements ProductCategoryService {
    @Override
    public ProductCategory getCategory(String id) {
        return getById(id);
    }

    @Override
    public String addCategory(Map<String, Object> params) {
        try{
            ProductCategory productCategory = parseCategory(params);
            save(productCategory);
            return "success";
        }catch (Exception e){
            throw new RuntimeException("添加商品失败"+e.getMessage());
        }
    }

    @Override
    public List<ProductCategory> getAll() {
        return list();
    }

    @Override
    public List<ProductCategory> getTop() {
        return baseMapper.findTopCategory();
    }

    @Override
    public List<ProductCategory> getChild(int id) {
        return baseMapper.findChildCategory(id);
    }

    @Override
    public String updateCategory(Map<String, Object> params) {
        try{
            ProductCategory productCategory = parseCategory(params);
            UpdateWrapper<ProductCategory> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", productCategory.getId());
            update(productCategory, updateWrapper);
            return "success";
        }catch (Exception e){
            throw new RuntimeException("更新分类失败"+e.getMessage());
        }
    }

    @Override
    public String deleteCategory(Integer id) {
        try{
            removeById(id);
            return "success";
        }catch (Exception e){
            throw new RuntimeException("删除分类失败"+e.getMessage());
        }
    }

    public ProductCategory parseCategory(Map<String, Object> params){
        ProductCategory productCategory = new ProductCategory();

        productCategory.setId(ParamUtil.parseParams(params,"id"));
        productCategory.setName(ParamUtil.parseParams(params,"name"));
        productCategory.setParentId(ParamUtil.parseParams(params,"parentId"));
        productCategory.setType(ParamUtil.parseParamsInt(params,"type"));

        return productCategory;
    }

}
